<?php

class Resource {

    var $src;
    var $a;
    
    function Resource () {
        $this->a = array ();
    }

    function source ($url) {
        if (empty ($this->src)) {
            $ch = curl_init ($url); 
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
            $this->src = curl_exec ($ch);
        }
        return $this->src;
    }

    function links () {
        if (empty ($this->a)) {
            if (preg_match_all ('/<[aA]+ (.+?)>(.+?)<\/[aA]+>/', $this->src, $regs, PREG_SET_ORDER)) {
                foreach ($regs as $reg) {
                    $this->a[] = new Anchor ($reg);
                }
            }
        }
        return $this->a;
    }
    
}

class Anchor {

    var $text;
    var $attr;

    function Anchor ($arr) {
        foreach (split (' ', $arr[1]) as $attr) {
            list ($key, $value) = split ('=', $attr);
            $this->attr[strtolower ($key)] = trim ($value, '"');
        }
        $this->text = $arr[2];
    }

    function attribute ($key) {
        return (isset ($this->attr[$key]) ? $this->attr[$key]:NULL);
    }

    function is_absolut () {
        return (ereg ("^http://", $this->attribute ('href')) ? TRUE:FALSE);
    }

}

$urls =
    array (
        'http://lloc.de/',
        'http://www.freely.de',
        'http://www.bowling.bz',
    );

?>
<html>
    <head>
        <title>Linkcheck</title>
    </head>
    <body>
        <h1>Linkcheck</h1>
<?php

foreach ($urls as $url) {

?>
        <h2><?php echo $url; ?></h2>
<?php

    $res = new Resource ();
    $res->source ($url);
    $links = $res->links ();
    $count = 0;
    if (!empty ($links)) {
?>
        <ul>
<?php

        foreach ($links as $link) {
            if ($link->is_absolut () && !ereg ($url, $link->attribute ('href'))) {

?>
            <li>
                <a href="<?php echo $link->attribute ('href'); ?>"><?php echo $link->attribute ('href'); ?></a>
                <?php echo ': ' . ($link->attribute ('rel') == "nofollow" ? "KO":"OK"); ?>
            </li>
<?php

                $count++;
            }
        }

?>
        </ul>
<?php
    
    }
    else {
    
?>
        <p>There is nothing!</p>
<?php

    }

?>
        <p><?php echo $count; ?> external links.</p>
<?php

}

?>
    </body>
</html>
